from onlineapidoc.model import Page, Space, Template, PAGE_TYPE_DIR, lang_codes
from sqlobject.sqlbuilder import Update
import cherrypy
import Cheetah.Filters
import time

"""
key string for template, these keys in template will be replaced by server automaticlly
"""
dict_c_mark = {"title":"c_mark_title",
               "action":"c_mark_action",
               "page_id":"c_mark_page_id",
               "page_path":"c_mark_page_path",
               "page_release":"c_mark_page_release",
               "page_lang":"c_mark_page_lang",
               "space_name":"c_mark_space_name",
               "space_id":"c_mark_space_id",
               "page_encoding":"c_mark_page_encoding",
               "page_ext_info":"c_mark_page_with_info"}

def jsback(step=-1):
    return "<script LANGUAGE=\"JavaScript\">\nhistory.go(" + str(step) + ");\n</script>"


class USDNException(Exception):
    """
    Base class for exceptions in this project
    """
    pass

class UE_no_special_cookie(USDNException):
    def __init__(self, cookiename, defaultvalue):
        Exception.__init__(self)
        self.cookiename = cookiename
        self.defaultvalue = defaultvalue

def set_cookie(cookie_name, cookie_value):
    cookie = cherrypy.response.simpleCookie
    cookie[cookie_name] = cookie_value
    cookie[cookie_name]['path'] = '/'
    gmt_expiration_time = time.gmtime(time.time() + (365 * 24 * 60 * 60))   #  1 year, in seconds
    cookie[cookie_name]['expires'] = time.strftime("%a, %d-%b-%Y %H:%M:%S GMT", gmt_expiration_time)
    return None
    
def get_cookie(cookie_name, default_ret=None):
    if cherrypy.request.simpleCookie.has_key(cookie_name):
        return cherrypy.request.simpleCookie[cookie_name].value
    else:
        return default_ret    

def delete_cookie(cookie_name):
    cherrypy.response.simpleCookie[cookie_name] = ''
    cherrypy.response.simpleCookie[cookie_name]['expires'] = 0

def set_session(session_name, session_value):
    cherrypy.session[session_name] = session_value
    
def get_session(session_name):
    return cherrypy.session.get(session_name)

def doutf8(unicodeStr):
    return unicodeStr.encode('utf-8')

def get_space_family_lang(space):
    """
    Get the language string and corresponding space's id.
    """
    dict_family = {}
    
    if (space.parent_space):
        sp = space.parent_space
    else:
        sp = space
        
    dict_family[lang_codes[sp.language]] = sp.id

    for child in sp.children_space:
        dict_family[lang_codes[child.language]] = child.id

    return dict_family

def get_primary_page(page):
    if page.primary_copy:
        return page.primary_copy
    else:
        return page

def get_page_family_lang(page):
    """
    Get the language string and corresponding space's id.
    """
    dict_family = SortedDict()
    langid = page.space.language
    
    ipage = get_primary_page(page)

    dict_family[lang_codes[ipage.space.language]] = ipage.id

    for child in ipage.link_copies:
        if child.space.language == langid:
            dict_family.insert(lang_codes[child.space.language], child.id)
        else:
            dict_family[lang_codes[child.space.language]] = child.id

    return dict_family

def get_page_family_lang_no_trans(page):
    """
    Get the need to be translated page with and corresponding space's id a special language.
    """
    dict_family = SortedDict()
    langid = page.space.language
    
    ipage = get_primary_page(page)
    lpage = None

    for child in ipage.space.children_space:
        lpage = get_matching_lang_page(ipage, child.language)
        if not lpage:
            dict_family[lang_codes[child.language]] = child.id

    return dict_family

def get_matching_lang_page(page, langid):
    if not page:
        return None
    ipage = get_primary_page(page)
    
    if ipage.space.language == langid:
        return ipage
    else:
        for child in ipage.link_copies:
            if child.space.language == langid:
                return child

    return None     #there is no matched page

def do_duplicate_page(page, space, with_content, parent):
    if with_content:
        content = page.content
    else:
        content = None

    new_page = Page(name=page.name,
                    content=content,
                    space=space,
                    parent_page=parent,
                    type=page.type,
                    template=page.template,
                    last_edit_user=space.admin,
                    version=1,
                    primary_copy=page)

    #create sub pages recursely
    if new_page.type==PAGE_TYPE_DIR:
        for sub_page in page.sub_pages:
            do_duplicate_page(sub_page, space, with_content, new_page)
    
    return new_page

dictdoutf8 = lambda d : dict((k.encode('utf-8'), d[k].encode('utf-8') ) for k in d)

unilist = lambda l : list(eval('u"""'+k+'"""') for k in l)

class SortedDict(dict): 
    "A dictionary that keeps its keys in the order in which they're inserted." 
    def __init__(self, data=None): 
        if data is None: data = {} 
        dict.__init__(self, data) 
        self.keyOrder = data.keys() 
 
    def __setitem__(self, key, value): 
        dict.__setitem__(self, key, value) 
        if key not in self.keyOrder: 
            self.keyOrder.append(key) 
 
    def __delitem__(self, key): 
        dict.__delitem__(self, key) 
        self.keyOrder.remove(key) 
 
    def __iter__(self): 
        for k in self.keyOrder: 
            yield k 
 
    def items(self): 
        return zip(self.keyOrder, self.values()) 
 
    def keys(self): 
        return self.keyOrder[:] 
 
    def values(self): 
        return [dict.__getitem__(self, k) for k in self.keyOrder] 
 
    def update(self, dict): 
        for k, v in dict.items(): 
            self.__setitem__(k, v) 
 
    def setdefault(self, key, default): 
        if key not in self.keyOrder: 
            self.keyOrder.append(key) 
        return dict.setdefault(self, key, default) 
 
    def insert(self, key, value): 
        dict.__setitem__(self, key, value) 
        if key not in self.keyOrder:
            self.keyOrder.insert(0, key) 

    def value_for_index(self, index): 
        "Returns the value of the item at the given zero-based index." 
        return self[self.keyOrder[index]] 
 
    def copy(self): 
        "Returns a copy of this object." 
        # This way of initializing the copy means it works for subclasses, too. 
        obj = self.__class__(self) 
        obj.keyOrder = self.keyOrder 
        return obj 
  
    def __repr__(self): 
        """ 
        Replaces the normal dict.__repr__ with a version that returns the keys 
        in their sorted order. 
        """ 
        return '{%s}' % ', '.join(['%r: %r' % (k, v) for k, v in self.items()]) 
